﻿using System;
using System.Web;
using System.Web.Security;
using System.Web.UI.WebControls;

namespace Ewma.Account
{
    //http://www.codeproject.com/Articles/46369/Improved-ASP-NET-Password-Recovery

    public partial class ForgottenPassword : System.Web.UI.Page
    {
        protected void Page_Load (object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                Literal personname = ((Literal)PWRecovery.QuestionTemplateContainer.FindControl ("personname"));
                try
                {
                    personname.Text = Request.Cookies["usernameCookie"].Value;
                }
                catch
                {
                    personname.Text = "Beuh...";
                }
            }
        }
        protected void validateUserEmail (object sender, LoginCancelEventArgs e)
        {
            
            TextBox EmailAddressTB = ((TextBox)PWRecovery.UserNameTemplateContainer.FindControl ("EmailAddressTB"));

            Literal ErrorLiteral = ((Literal)PWRecovery.UserNameTemplateContainer.FindControl ("ErrorLiteral"));
            CheckBox NotRobot = (CheckBox)PWRecovery.UserNameTemplateContainer.FindControl ("notrobot");

            MembershipUser mu = Membership.GetUser (PWRecovery.UserName);

            if (!NotRobot.Checked)
            {
                e.Cancel = true;
                ErrorLiteral.Text = "Please prove that you are not a robot";
            }
            else if (mu != null) // The username exists
            {
                if (mu.Email.Equals (EmailAddressTB.Text)) // Their email matches
                {
                    /*ProfileCommon newProfile = Profile.GetProfile (PWRecovery.UserName);
                    HttpCookie appCookie = new HttpCookie ("usernameCookie");
                    appCookie.Value = newProfile.FullName;
                    appCookie.Expires = DateTime.Now.AddMinutes (3);
                    Response.Cookies.Add (appCookie);*/
                }
                else
                {
                    e.Cancel = true;
                    ErrorLiteral.Text = "Your username and password do not match";
                }
            }
            else
            {
                e.Cancel = true;
                ErrorLiteral.Text = "No such user found.";
                foreach (var v in Membership.GetAllUsers ())
                {
                    if (v is MembershipUser)
                    {
                        MembershipUser u = (MembershipUser)v;
                        ErrorLiteral.Text = ErrorLiteral.Text + "," + u.Email + "," + u.UserName;
                    }
                    else
                    {
                        ErrorLiteral.Text = v.GetType ().ToString ();
                    }
                }
            }
        }
    }
}